IF OBJECT_ID('ssf.utl_sequence_number') IS NOT NULL
	DROP FUNCTION ssf.utl_sequence_number
GO

CREATE FUNCTION ssf.utl_sequence_number (
	@count BIGINT
)
RETURNS TABLE
AS
RETURN (
	WITH
	T4 (i) AS (
		SELECT i
		FROM (
			VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)
		) AS t(i)
	) -- 2^4 = 16
	, T8 (i) AS (
		SELECT a.i
		FROM T4 a
		CROSS JOIN T4 b
	) -- 2^8 = 256
	, T16 (i) AS (
		SELECT a.i
		FROM T8 a
		CROSS JOIN T8 b
	) -- 2^16 = 65536
	, T32 (i) AS (
		SELECT a.i
		FROM T16 a
		CROSS JOIN T16 b
	) -- 2^32 = 4294967296
	, T63 (i) AS (
		SELECT TOP(
			CASE WHEN ISNULL(@count, 9223372036854775807) < 9223372036854775807
				THEN ISNULL(@count, 9223372036854775807)
				ELSE CAST(9223372036854775807 AS BIGINT)
				END
		) a.i -- using CASE statement is faster than just a value, not sure why???
		FROM T32 a
		CROSS JOIN T32 b
	) -- T32 * T32 = 2^64, but limit to max BIGINT, 9223372036854775807 (2^63 - 1)
	, SEQUENCE (n) AS (
		SELECT ROW_NUMBER() OVER (ORDER BY i)
		FROM T63
	)
	SELECT n
	FROM SEQUENCE
);
GO
